import Vue from 'vue'
import VueRouter from 'vue-router'
import Reg from '@/views/Reg/Reg'
import Login from '@/views/Login/Login'
import Main from '@/views/main/main'
import store from '@/store/index'
import Home from '@/views/Menus/Home/Home'
import UserInfo from '@/views/Menus/User/UserInfo'
import UserAvatar from '@/views/Menus/User/UserAvatar'
import UserPwd from '@/views/Menus/User/UserPwd'
import ArtCate from '@/views/Menus/Article/ArtCate1'
import ArtList from '@/views/Menus/Article/ArtList'



Vue.use(VueRouter)

const routes = [
  // 配置路由规则对象
  {
    path: '/login',
    component: Login
  },
  {
    path: '/reg',
    component: Reg
  },
  {
    path: '/',
    component: Main,
    // 路由重定向 
    redirect: '/home',
    // 二级路由
    children: [
      {
        path: 'home',
        component: Home,
      },
      {
        path: 'user-info',
        component: UserInfo,
      },
      {
        path: 'user-avatar',
        component: UserAvatar,
      },
      {
        path: 'user-pwd',
        component: UserPwd,
      },
      {
        path: 'art-cate',
        component: ArtCate,
      },
      {
        path: 'art-list',
        component: ArtList,
      },
    ]
  }

]

const router = new VueRouter({
  routes
})

//路由守卫
// to去哪里 from来自哪里 放行next()  阻止next() next('/路径/')
router.beforeEach((to, from, next) => {
  // 如果用户没有登录 token 并访问/my 开头的 就阻止 
  const token = store.state.token
  // 如果没有token 且访问的不是login 且访问的是reg
  if (!token && to.path !== '/login' && to.path !== '/reg') {
    // 跳转login
    next('/login')
  } else {
    // 否则放行
    next()
  }
  // 如果访问的是 /login || /reg 直接放行
  // if (to.path === '/login' || to.path === '/reg') {
  //   next()
  // } else {
  //   if (!token) {
  //    next('login')
  //   } else {
  //     next()
  //  }
  // }
})



export default router
